# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router


router.get '/', (req, res, next) ->
    if not req.session.host
        return next new Error('请先选择待配置的主机')
    res.redirect '/i/091/1'


router.get '/:mode', (req, res, next) ->
    if not req.session.host
        return next new Error('请先选择待配置的主机')

    res.locals.mode = parseInt(req.params.mode)

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    res.locals.mode_1_disabled = true
    res.locals.mode_2_disabled = true
    res.locals.mode_3_disabled = true

    await client.query \
        "select mode, disabled from pay_i_091 where host = $1", [
            req.session.host.uuid
        ], defer err, result
    if err then done(client); return next(err)
    for row in result.rows
        switch row.mode
            when 1 then res.locals.mode_1_disabled = row.disabled
            when 2 then res.locals.mode_2_disabled = row.disabled
            when 3 then res.locals.mode_3_disabled = row.disabled

    await client.query \
        "select * from pay_i_091 where host = $1 and mode = $2 limit 1", [
            req.session.host.uuid,
            res.locals.mode
        ], defer err, result
    if err then done(client); return next(err)

    # 如果还没有配置，则自动生成默认配置
    if result.rows.length == 0
        await client.query \
            "insert into pay_i_091 (
                uuid, host, mode, listen_addr, listen_port, timeout, notes
            ) values (
                $1, $2, $3, 1, trunc(random() * 49999), 30,
                'POS 009.1 接入服务配置'
            )", [
                uuid.v4(), req.session.host.uuid, res.locals.mode
            ], defer err, result
        if err then done(client); return next(err)
        done()
        return res.redirect "/i/091/#{res.locals.mode}"
    else
        done()
        return res.render 'i/091', record: result.rows[0]


router.post '/edit/:mode', (req, res, next) ->
    for k in ['listen_addr', 'listen_port', 'timeout']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    res.locals.mode = parseInt(req.params.mode)

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_i_091 set
            listen_addr = $1, listen_port = $2, timeout = $3, notes = $4
            where uuid = $5 and host = $6 and mode = $7", [
            parseInt(req.body.listen_addr),
            parseInt(req.body.listen_port),
            parseInt(req.body.timeout),
            req.body.notes,
            req.body.uuid, req.session.host.uuid, res.locals.mode
        ], defer err, result
    if err then done(client); return next(err)

    # 通过数据库发送通知给监听客户端
    await client.query """
        notify pay_i_091, '{
            host: "#{req.session.host.uuid}",
            uuid: "#{req.body.uuid}"
        }'
    """, defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect "/i/091/#{res.locals.mode}"


router.post '/disable/:mode', (req, res, next) ->
    res.type('json')
    for k in ['uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    res.locals.mode = parseInt(req.params.mode)

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_i_091 set disabled = $1
            where uuid = $2 and host = $3 and mode = $4", [
            req.body.disabled,
            req.body.uuid, req.session.host.uuid, res.locals.mode
        ], defer err, result
    if err then done(client); return next(err)

    # 通过数据库发送通知给监听客户端
    await client.query """
        notify pay_i_091, '{
            host: "#{req.session.host.uuid}",
            uuid: "#{req.body.uuid}"
        }'
    """, defer err, result
    if err then done(client); return next(err)
    done()
    res.json succ: true, redirect: "/i/091/#{res.locals.mode}"
